# -*- coding: utf-8 -*-

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import logging,os

from functools import wraps
import gmemsess


class BaseRequestHandler(webapp.RequestHandler):

    def render(self,template_file,template_values={}):
        """
        Helper method to render the appropriate template
        """
        path = os.path.join(os.path.dirname(__file__), template_file)
        self.response.out.write(template.render(path, template_values))
        
    def param(self, name, **kw):
        return self.request.get(name, **kw)
    
    
def checkLogin(method):
    '''
    检查用户是否登录
    '''
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if not getUsername(self):
            self.redirect('/')
        else:
            return method(self, *args, **kwargs)
    return wrapper

#def requires_admin(method):
#    from google.appengine.api import users
#    @wraps(method)
#    def wrapper(self, *args, **kwargs):
#        if not self.is_login:
#            self.redirect(users.create_login_url(self.request.uri))
#            return
#        elif not (self.is_admin
#            or self.author):
#            return self.error(403)
#        else:
#            return method(self, *args, **kwargs)
#    return wrapper

def getUsername(self):
    sess = gmemsess.Session(self)
    return sess['username']

def getUserKey(self):
    sess = gmemsess.Session(self) 
    return sess['user_key']